package es.kivitel.android.sms.gui;


import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import es.kivitel.android.sms.R;
import es.kivitel.android.sms.kernel.DatabaseManager;

public class MonthScheduler extends Activity{
	private static final String TAG = MonthScheduler.class.getName();
	private static final int MENU_BACK = 0;
	private static final int MENU_QUIT = 1;
	private static final int MENU_HELP = 2;
	String[] monthName = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", 
						  "Aug", "Sep", "Oct", "Nov", "Dec"};
    //Calendar: Month goes from 0 to 11,
   	//Week days are from 1 (Sunday) to 7 (Saturday)
    //Day of month begins at 1 (warning: 0 refers to the previous month)      	
	Calendar cInstance;
	GridView gv;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       	setContentView(R.layout.month_activity);
       	gv = (GridView) findViewById(R.id.ButtonGridView);	          	
	    cInstance = Calendar.getInstance();
	    cInstance.set(Calendar.HOUR,0);
	    cInstance.set(Calendar.MINUTE,0);
	    cInstance.set(Calendar.SECOND,0);
	    cInstance.set(Calendar.MILLISECOND,0);	    
	    gv.setAdapter( new ButtonAdapter(cInstance) );   
	    
	    // Watches events button
	    final Button btLeftMonth = (Button) findViewById(R.id.BtnLeftMonth);
	    btLeftMonth.setOnClickListener(new View.OnClickListener() {
	    	// Performs action on click
	        public void onClick(View v) {
	        	cInstance.set( Calendar.MONTH, cInstance.get(Calendar.MONTH) -1 );
	    	    gv.setAdapter( new ButtonAdapter(cInstance));
	        } 
	    }); 	
	    
	    // Watch events button
	    final Button btRightMonth = (Button) findViewById(R.id.BtnRightMonth);
	    btRightMonth.setOnClickListener(new View.OnClickListener() {
	    	// Perform action on click
	        public void onClick(View v) {
	        	cInstance.set( Calendar.MONTH, cInstance.get(Calendar.MONTH) + 1 );
	    	    gv.setAdapter( new ButtonAdapter(cInstance));
	        } 
	    }); 			   
   }	
	
    public class ButtonAdapter extends BaseAdapter {
        
        Calendar cal;         
        int dayInit;//The day of the week the month begins

        //A calendar instance is passed to control months
        public ButtonAdapter(Calendar _cInstance) {
            cal = _cInstance;
            _initMonth();
        }
        
        private void _initMonth(){
            cal.set( Calendar.DAY_OF_MONTH, 1); 
            dayInit = cal.get( Calendar.DAY_OF_WEEK ) -1; // -1 because count begins in 1 and not in 0
            
            String year = " (" + String.valueOf(cal.get( Calendar.YEAR ))+")";           
            final TextView tv = (TextView) findViewById(R.id.title);
            tv.setText( monthName[cal.get( Calendar.MONTH )] + year );
            
            Button btL = (Button) findViewById(R.id.BtnLeftMonth);
            btL.setText( monthName[(cal.get( Calendar.MONTH ) +11)% 12]);
            Button btR = (Button) findViewById(R.id.BtnRightMonth);
            btR.setText( monthName[(cal.get( Calendar.MONTH ) + 1)% 12]);
            
        }

        public int getCount() {
            return ( cal.getActualMaximum( Calendar.DAY_OF_MONTH ) +  dayInit);
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        // create a new ImageView for each item referenced by the Adapter
        public View getView(int position, View convertView, ViewGroup parent) {
            Button bt;
            Calendar dayReviewed;
            int state, day = position - dayInit +1; // when position == dayInit, we want day = 1;            
            if( day > 0 ){          
            	bt = new Button(parent.getContext());
            	bt.setLayoutParams(new GridView.LayoutParams(40, 70));
            	bt.setPadding(1, 1, 1, 1);
            	//We'll check whether exists any event or not
            	dayReviewed= (Calendar) cInstance.clone();
            	dayReviewed.set(Calendar.DAY_OF_MONTH, day);
            	state = DatabaseManager.checkProgrammedEvents(dayReviewed);
            	switch(state){
            	case 0: bt.setBackgroundResource(R.drawable.simple_button);            			
            		break;
            	case 1: bt.setBackgroundResource(R.drawable.today_btn);
            		break;
            	case 2: bt.setBackgroundResource(R.drawable.eventtoday_btn);
            		break;
            	case 3: bt.setBackgroundResource(R.drawable.event_btn);
            		break;
            	case 4: bt.setBackgroundResource(R.drawable.past_eventnotsent_btn);
            		break;
            	case 5: bt.setBackgroundResource(R.drawable.past_eventsent_btn);
            		break;
            	default:
            		break;            	
            	}            			
	            bt.setText( String.valueOf( day ) ); //added 1 because days begin in '1', not in '0'
	            bt.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						Calendar day = (Calendar) cInstance.clone();
						day.set(Calendar.DAY_OF_MONTH, Integer.parseInt(((Button)v).getText().toString()));						
						Bundle bundle = new Bundle();
						bundle.putLong(EventAdapterActivity.listingDate,day.getTimeInMillis());						
						Intent i = new Intent(v.getContext(),EventAdapterActivity.class);
						i.putExtras(bundle);
						startActivityForResult(i, MainActivity.CLOSING);
					}
				});
            }
            else{          	
            	bt = new Button(parent.getContext());
            	bt.setClickable(false);
            	bt.setLayoutParams(new GridView.LayoutParams(40, 70));
            	bt.setPadding(1, 1, 1, 1);
            	bt.setVisibility(View.INVISIBLE);
            	bt.setFocusable(false);
            }            
            return bt;            

        }
    }
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MonthScheduler.MENU_HELP, 0, getResources().getString(R.string.MenuHelp)).setIcon(android.R.drawable.ic_menu_info_details);        
        menu.add(0, MonthScheduler.MENU_BACK, 0, getResources().getString(R.string.MenuBack)).setIcon(android.R.drawable.ic_menu_revert);
        menu.add(0, MonthScheduler.MENU_QUIT, 0, getResources().getString(R.string.MenuQuit)).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
        return true;
    }

    /* Handles item selections */
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MonthScheduler.MENU_BACK:
        	startActivityForResult(new Intent(this,MainActivity.class), MainActivity.CLOSING);
        	finish();
            return true;
        case MonthScheduler.MENU_HELP:
            final CharSequence[] items = {"This calendar includes the following highlights:\nRed: during this day at least one event was programmed and wasn' sent.\nBlue: an event is programmed for this day and still hasn't been reached\nRed border- today Green: all the past events were programmed and sent"};
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Application info: Calendar");
            builder.setItems(items, new DialogInterface.OnClickListener() {				
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});        	
            builder.create();
            return true;
        case MonthScheduler.MENU_QUIT:
        	Bundle bundle = new Bundle();
        	bundle.putInt(MainActivity.CLOSING_PARAM, 1);
        	Intent i = new Intent(this,MainActivity.class);
        	i.putExtras(bundle);
        	setResult(RESULT_OK, i);
        	DatabaseManager.close();
        	finish(); 
            return true;
        }
        return false;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	Bundle extras = getIntent().getExtras();
    	if(extras!=null)
    		if(extras.getInt(MainActivity.CLOSING_PARAM) == 1) finish();  	
    }
}
